package com.briup.jdbc;

import java.sql.*;

/**
 * sql注入问题
 *  利用字符串拼接的sql语句，传递一些sql脚本，从而改变sql语义，跳过安全检查
 * 解决sql注入
 *  利用PreparedStatement进行预编译
 */
public class Test6 {
    public static final String driver = "com.mysql.cj.jdbc.Driver";
    public static final String url = "jdbc:mysql:///db01";
    public static final String username = "root";
    public static final String password = "rootroot";
    public static void main(String[] args) throws Exception {
        String name = "abc' or 1=1;-- ";
        String pwd = "";
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url,username,password);

        /*
        Statement statement = connection.createStatement();
        String sql = "select count(*) from t_user where name = '"+name+"' and password = '"+pwd+"'";
        */
        String sql = "select count(*) from t_user where name = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        System.out.println("sql = " + sql);
        // 预编译的sql语句，在执行之前，记得赋值
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,pwd);
        ResultSet resultSet = preparedStatement.executeQuery();
        resultSet.next();
        int anInt = resultSet.getInt(1);
        if(anInt == 0){
            System.out.println("登陆失败");
        }else{
            System.out.println("登陆成功");
        }

        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
